<?php
class UsersController extends AppController {
    public $helpers = array('Html', 'Form');
	
	public function index() {
        $this->set('users', $this->User->find('all'));
    }
	public function add() {
        if ($this->request->is('post')) {
            $d = $this->request->data;
			$d['User']['id'] = null;
			$d['User']['lastlogin'] = '2009-08-08 12:17:00';
			if(!empty($d['User']['password'])){
			   $d['User']['password'] = Security::hash($d['User']['password'],null,true);
			}
            if($this->User->save($d,true,array('username','password','role','email','phone','firstname','lastname','professional','getnews'))){
			    $link = array('controller'=>'users','action'=>'activate',$this->User->id.'-'.md5($d['User']['password']));
				App::uses('CakeEmail','Network/Email');
				$mail = new CakeEmail();
				$mail->from('noreply@localhost.com')
				->to($d['User']['email'])
				->subject('Test :: Inscription')
				->emailFormat('html')
				->template('add')
				->viewVars(array('username'=>$d['User']['username'],'link'=>$link))
				->send();
                $this->Session->setFlash("Votre compte a bien été créé");
                $this->redirect(array('action' => 'index'));
            }else {
                $this->Session->setFlash('Impossible de vous enregistrer.');
            }
        }
    }
	
	function login(){
	         if ($this->request->is('post')) {
			   if($this->Auth->login()){
			            $this->User->id = $this->Auth->user("id");
						$this->User->saveField('lastlogin',date('y-m-d H:i:s'));
			            $this->Session->setFlash("Vous étes maitenant connecté.");
			            $this->redirect(array('action' => 'index'));
			   }else{
			            $this->Session->setFlash("Identifiant incorrects.");
			   }
			 }
	
	}
	function logout(){
	   $this->Auth->logout();
	   $this->redirect('/');
	}
	
	function activate($token){
	    $token = explode('-',$token);
		$user = $this->User->find('first',array(
		   'conditions' => array('id' => $token[0],'MD5(User.password)'=> $token[1]),'active' => 0)
		);
		if(!empty($user)){
		   $this->User->id = $user['User']['id'];
		   $this->User->saveField('active',1);
		   $this->Session->setFlash("Votre compte a bien été activé.");
		   $this->Auth->login($user['User']);
		}else{
		    $this->Session->setFlash("Ce lien d'activation n'est pas valide");
		}
		$this->redirect(array('action' => 'index'));
		die();
	}
	
	function password(){
	          if(!empty($this->request->params['named']['token'])){
			          $token = $this->request->params['named']['token'];
					  $token = explode('-',$token);
		              $user = $this->User->find('first',array('condition' => array('id' => $token[0],'MD5(User.password)'=> $token[1],'active' => 1)));
			        if($user){
			            $this->User->id = $user['User']['id'];
				        $password = substr(md5(uniqid(rand(),true)),0,8);
				        $this->User->saveField('password',Security::hash($password,null,true));
				        $this->Session->setFlash("Votre mot de passe a bien été réinitialisé, voici votre vouveau mot de passe : $password");
			        }else{
			            $this->Session->setFlash("Le lien n'est pas valide");
			        }
			  }
	          if($this->request->is('post')){
			     $v = current($this->request->data);
				 $user = $this->User->find('first',array('condition' => array('mail' =>$v['mail'],'active'=>1)));
				 if(empty($user)){
				     $this->Session->setFlash("Aucun utilisateur ne correspond à ce mail");
				 }else{
				    App::uses('CakeEmail','Network/Email');
				    $link = array('controller'=>'users','action'=>'password','token' => $user['User']['id'].'-'.md5($user['User']['password']));
				    $mail = new CakeEmail();
				    $mail->from('noreply@localhost.com')
				    ->to($user['User']['email'])
				    ->subject('Test :: Mot de passe oublié')
				    ->emailFormat('html')
				    ->template('mdp')
				    ->viewVars(array('username'=>$user['User']['username'],'link'=>$link))
				    ->send();
					$this->Session->setFlash("Veuillez vérifier votre boite de réception");
				 }
			  }
	}
	
	public function edit() {
	$user_id = $this->Auth->user('id');
    if (!$user_id) {
	      $this->redirect('/');
		  die();
    }
	$this->User->id = $user_id;
    $passError = false;
    if ($this->request->is('post') || $this->request->is('put')) {
	    $d = $this->request->data;
		$d['User']['id'] = $user_id;
		if(!empty($d['User']['pass1'])){
		       if($d['User']['pass1']==$d['User']['pass2']){
			          $d['User']['password'] = Security::hash($d['User']['pass1'],null,true);
			   }else{
			        $passError = true;
			   }
		}
        if ($this->User->save($d,true,array('username','password','role','email','phone','firstname','lastname','professional','getnews'))) {
            $this->Session->setFlash("Votre profil a bien été édité");
        } else {
            $this->Session->setFlash("Impossible de sauvegarder");
        }
		if($passError) $this->User->validationErrors['pass2'] = array('Les mot de passe ne correpondent pas');
	}else{
	   $this->request->data = $this->User->read();
	} 
   $this->request->data['User']['pass1'] = $this->request->data['User']['pass2'] = '';	
}
    public function delete($id) {
    if ($this->request->is('get')) {
        throw new MethodNotAllowedException();
    }
    if ($this->User->delete($id)) {
        $this->Session->setFlash('L\'utilisateur avec l\'id ' . $id . ' a été supprimé.');
        $this->redirect(array('action' => 'index'));
    }
  }
  
  function membre(){
  
  }
}
?>